<template>
    <div class="isCloseTableStyle">
        <vxe-table
            show-overflow
            border
            stripe
            :expand-config="{ iconOpen: 'el-icon-remove', iconClose: 'el-icon-circle-plus' }"
            ref="xTable"
            resizable
            :data="dataSource"
            highlight-hover-row
            style="width: 100%"
            v-loading="tableLoading"
            auto-resize
            show-header-overflow
        >
            <vxe-table-column type="expand" width="60px">
                <template #content="{ row, rowIndex }">
                    <div class="expand-wrapper">
                        <span v-if="getDirectMode(row, rowIndex)" :key="key + rowIndex" style="font-size: 13px; font-weight: 700">{{
                            '计算模式:' + directModeTypes[getDirectMode(row, rowIndex)]
                        }}</span>
                        <div v-for="(value1, key1) in getData(row, rowIndex)" :key="key1 + rowIndex" style="margin: 2px 0">
                            <span style="font-size: 13px; font-weight: 700">{{ DATA_TYPE[key1] + ':' + numberFormat(value1) }}</span>
                            <el-popover placement="right" width="800" trigger="hover">
                                <!-- <div>
                                    <span style="font-weight: 700">统计表名：</span>
                                    {{ (dataBasic[rowIndex][key1] || {}).calculateTable }}&nbsp;
                                    {{
                                        '(' +
                                            ((columnComments.find(item => item.tableName === (dataBasic[rowIndex][key1] || {}).calculateTable) || {})
                                                .tableComments || '') +
                                            ')' || {}
                                    }}
                                </div>
                                <div>
                                    <span style="font-weight: 700">统计主键：</span>
                                    {{ (dataBasic[rowIndex][key1] || {}).calculateTableKey }}&nbsp;
                                    {{
                                        getFieldName(
                                            columnComments.filter(item => item.tableName === (dataBasic[rowIndex][key1] || {}).calculateTable) || {},
                                            (dataBasic[rowIndex][key1] || {}).calculateTableKey,
                                            true
                                        )
                                    }}
                                </div>
                                <div>
                                    <span style="font-weight: 700">统计字段：</span>
                                    {{ (dataBasic[rowIndex][key1] || {}).calculateField }}&nbsp;
                                    {{
                                        getFieldName(
                                            columnComments.filter(item => item.tableName === (dataBasic[rowIndex][key1] || {}).calculateTable) || {},
                                            (dataBasic[rowIndex][key1] || {}).calculateField,
                                            true
                                        )
                                    }}
                                </div> -->
                                <risk-table
                                    :msg="{
                                        returnData: { list: dataDetails[rowIndex][key1] },
                                        dataKey: 'list',
                                        title: dnColumn[rowIndex][key1],
                                        checked: { on: false, option: false },
                                        hidePage: true,
                                        maxHeight: '200px',
                                    }"
                                    :key="listMsgNumKey + 'listMsgNumKey'"
                                    style="padding: 5px"
                                    v-loading="detailTableLoading"
                                ></risk-table>
                                <el-tag slot="reference" style="margin-left: 6px; cursor: default"> 详情 </el-tag>
                            </el-popover>
                        </div>
                    </div>
                </template>
            </vxe-table-column>
            <!-- <vxe-table-column field="resultId" title="流水号" min-width="100"></vxe-table-column> -->
            <vxe-table-column field="entryCode" title="条目编码" min-width="100"></vxe-table-column>
            <vxe-table-column field="branchName" title="分支名称" min-width="100"></vxe-table-column>
            <vxe-table-column field="branchValue" title="分支值" min-width="120">
                <template #default="{ row }">
                    <span>{{ numberFormat(row.branchValue, 2) || '--' }}</span>
                </template>
            </vxe-table-column>
            <vxe-table-column field="branchNo" title="分支序号" min-width="120"></vxe-table-column>
            <vxe-table-column field="branchKey" title="静态分支KEY" min-width="120"></vxe-table-column>
        </vxe-table>
    </div>
</template>
<script lang="ts">
import RiskTable from '@/common/components/risk-table.vue';
import DictionConstUtil from '@/utils/diction-const-util';
import { getColumnComment } from '../api';
import { numberFormat } from '@/utils/tools';
import { Component, Vue, Prop } from 'vue-property-decorator';
@Component({
    name: 'InstReportDetail',
    components: {
        RiskTable,
    },
})
export default class SingleDetail extends Vue {
    numberFormat = numberFormat;
    @Prop() transRow: any;

    private DATA_TYPE = {
        INSTRUCTION_STRICT: '不利方向值',
        INSTRUCTION_WIDE: '有利方向值',
        EARLY: '日初持仓值',
        INSTRUCTION_LENIENT: '指令从宽',
    };

    private directModeTypes = {
        '0': '有序从严控制',
        '1': '有序非从严控制',
        '2': '无序从严控制',
        '3': '无序非从严控制',
    };

    private dataSource: any[] = []; // 表数据

    private tableLoading: boolean = true; // 表数据加载

    private detailTableLoading: boolean = false; // 详情表数据加载

    private columns: any[] = []; // 表头结构信息

    private columnComments: any[] = []; // 字段说明

    private value: any[] = []; // 详情格式

    private dataDetails: any[] = []; // 实际参数和值

    private dataBasic: any[] = []; // 基础参数

    private dnColumn: any[] = []; // 详情列

    private listMsgNumKey: number = 0; // listMsg表数据渲染Key

    private directMode: string[] = []; // 计算模式

    async mounted() {
        this.getStaticBranchResult();
    }

    // 获取结果信息
    private getStaticBranchResult(): void {
        this.dnColumn = [];
        this.tableLoading = true;
        // 历史指令分支结果
        let value = this.transRow.branchCalculateResults || [];

        if (value && value.length > 0) {
            value.forEach((item, i) => (item.key = item.branchKey + '-' + i));
            value.forEach((item, i) => (item.entryCode = this.transRow.entryCode));
            value.sort((a, b) => Number(a.branchNo) - Number(b.branchNo));
            this.dataSource = value;
            this.detailTableLoading = true;
            // 获取要查询的表的字段名
            let tableNames = [];
            let dt;
            this.dataSource.forEach(record => {
                dt = (record.calculateDetails || {}).dataBasic || {};
                for (let key in dt) {
                    if (!tableNames.includes(dt[key].calculateTable)) {
                        tableNames.push(dt[key].calculateTable);
                    }
                }
            });
            if (tableNames.length === 0) {
                this.columnComments = [];
                this.handleColumnComment();
                this.tableLoading = false;
            } else {
                getColumnComment(tableNames).then(res => {
                    this.columnComments = res || [];
                    this.handleColumnComment();
                });
            }
        } else {
            this.dataSource = [];
            this.tableLoading = false;
        }
    }

    private handleColumnComment() {
        this.dataSource.forEach((record, rowIndex) => {
            let detail = record.calculateDetails || {};
            // 基本格式
            this.dataBasic[rowIndex] = detail.dataBasic;
            // 获取所有统计主键
            let calculateTableKey = [];
            for (const key in this.dataBasic[rowIndex]) {
                if (this.dataBasic[rowIndex][key] && this.dataBasic[rowIndex][key]['calculateTableKey']) {
                    calculateTableKey.push(this.dataBasic[rowIndex][key]['calculateTableKey']);
                }
            }
            // 实际格式内容和数据
            this.dataDetails[rowIndex] = detail.dataDetails;
            // 计算模式
            this.directMode[rowIndex] = detail.directMode;
            // 大致格式名与值
            this.value[rowIndex] = record.branchCalulateTypeResults || {};
            let col = JSON.parse(JSON.stringify({}));
            for (let key in detail.dataBasic) {
                // 中文字段信息条
                let columnInfo = this.columnComments.filter(item => item.tableName == (this.dataBasic[rowIndex][key] || {}).calculateTable) || {};
                this.$set(col, key, []);
                // 获取表单字段中文名(dn为对应的英文字段)
                if (this.dataDetails[rowIndex][key]) {
                    for (let dn in this.dataDetails[rowIndex][key][0]) {
                        let needData = {
                            name: this.getFieldName(columnInfo, dn, false),
                            val: dn, // 英文字段
                            key: key,
                            minWidth: 100,
                            type: 'func',
                            funcBody: (value, row, val) =>
                                value != undefined && !calculateTableKey.includes(val) && val.toString().substr(0, 2) == 'N_'
                                    ? numberFormat(value, 2)
                                    : value || '--',
                        };
                        col[key].push(needData);
                    }
                }
            }
            this.dnColumn.push(col);
            this.detailTableLoading = false;
            this.tableLoading = false;
        });
    }

    // 字段名称获取
    private getFieldName(fieldComments, fieldName, action): string {
        switch (fieldName) {
            case 'C_FUND_NAME_ST':
                return '基金简称';
            case 'C_STOCK_NAME_ST':
                return '证券简称';
            case 'C_FD_AC_NAME':
                return '组合名称';
            case 'C_ASSET_NAME':
                return '资产单元名称';
            case 'C_SIMULATE_MESSAGE':
                return '信息来源';
            case 'N_DEAL_MARKET_VALUE47':
                return '基金现金资产（成交）';
            case 'N_MARKET_VALUE47':
                return '基金现金资产';
            default:
                break;
        }
        if (!fieldComments || !fieldName) {
            return '';
        }
        let fieldComment = (fieldComments.find(item3 => fieldName === item3.columnName) || {}).comments || '';
        if (action && fieldComment) {
            return '(' + fieldComment + ')';
        } else {
            return fieldComment;
        }
    }

    // 获取主表数据中的一条
    private getData(record, rowIndex): any {
        return this.value[rowIndex];
    }

    // 获取计算模式
    private getDirectMode(record, rowIndex): any {
        return this.directMode[rowIndex];
    }
}
</script>
<style lang="scss" scoped>
.container {
    .header-container-detail {
        border: 1px solid #ccc;
        margin-bottom: 10px;
    }
    .display-grid1 {
        display: grid;
        grid-template-columns: 25% 25% 25% 25%;
        height: 40px;
    }
    .display-grid2 {
        display: grid;
        grid-template-columns: 50% 50%;
        height: 40px;
    }
    .backGC {
        border: 1px solid #ccc;
        background-color: #f7f7f7;
    }
    .opened-content {
        margin-top: 5px;
        border: 1px solid #ccc;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
        width: 100% !important;
    }
    .boxStyle {
        margin: 40px 0 0 10px;
        width: 40px;
        height: 40px;
    }
    .iconStyle {
        color: #939398;
        font-size: 22px;
    }
}
/deep/ .vxe-table--render-default .vxe-body--expanded-cell {
    background-color: #d8e5f3;
    margin-left: 60px;
    padding: 3px;
}

/deep/ .el-tag {
    font-size: 12px;
    font-weight: 700;
    height: 26px;
    line-height: 26px;
}
// // 隐藏部分搜索条件
// .isCloseTableStyle /deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
//     height: calc(100vh - 220px) !important;
// }
// // 显示部分搜索条件
// .isOpenTableStyle /deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
//     height: calc(100vh - 350px);
// }
</style>
